package ee.android.kinokavad.adapters;

import java.util.List;
import java.util.Locale;

import org.joda.time.DateTime;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import ee.android.kinokavad.R;
import ee.android.kinokavad.data.Session;
import ee.android.kinokavad.utils.FontUtils;

public class SessionAdapter extends ArrayAdapter<Session>{

	private List<Session> sessions;
	private LayoutInflater inflater;
	public SessionAdapter(Context context, List<Session> sessions) {
		super(context, R.layout.session_row, sessions);
		this.sessions = sessions;
		inflater = LayoutInflater.from(context);
	}

	private static class ViewHolder {
		private TextView time;
		private TextView movieName;
		private View row;
		private TextView duration;
		private TextView movieGenre;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.session_row, null);
			holder.time = (TextView) convertView.findViewById(R.id.sessionRowTime);
			holder.movieName = (TextView) convertView.findViewById(R.id.sessionRowMovieName);
			holder.row = convertView.findViewById(R.id.sessionRowLayout);
			holder.duration = (TextView) convertView.findViewById(R.id.sessionRowMovieDuration);
			holder.movieGenre = (TextView) convertView.findViewById(R.id.sessionRowMovieGenre);
			convertView.setTag(holder);
			FontUtils.setRobotoFont(getContext(), convertView);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		Session session = sessions.get(position);
		holder.time.setText(new DateTime(session.getDateTime()).toString("HH:mm"));
		if (session.getMovieTitle() != null) {
			holder.movieName.setText(session.getMovieTitle());
		} else {
			holder.movieName.setText("");
		}
		
		if (session.isBeforeNow()) {
			holder.row.setBackgroundResource(R.drawable.list_selector_grey);
		} else {
			holder.row.setBackgroundResource(R.drawable.abs__list_selector_holo_light);
		}
		
		if (session.getDuration() != null
				&& !session.getDuration().toLowerCase(Locale.ENGLISH).equals("n/a")) {
			holder.duration.setText(session.getDuration());
			holder.duration.setVisibility(View.VISIBLE);
		} else {
			holder.duration.setText("");
			holder.duration.setVisibility(View.GONE);
		}
		
		if (session.getMovieGenre() != null) {
			holder.movieGenre.setText(session.getMovieGenre().replace(",", ", "));
			holder.movieGenre.setVisibility(View.VISIBLE);
		} else {
			holder.movieGenre.setVisibility(View.GONE);
			holder.movieGenre.setText("");
		}

		return convertView;
	}


}
